package com.acheli.registry.config;

import com.acheli.ACHeli;
import com.acheli.registry.factories.ACHFactories;
import com.acheli.registry.network.ACHMessages;
import com.acheli.registry.network.packet.GsonComponentFLRegistryC2SPacket;
import com.acheli.registry.resource.DynamicResourcePack;
import com.acheli.rideable.functionLathes.component.DefaultComponentFactoryRegistry;
import com.acheli.rideable.functionLathes.component.DefaultComponentProvider;
import com.google.gson.*;
import com.mojang.blaze3d.platform.NativeImage;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.resources.ResourceLocation;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.acheli.ACHeli.MODID;

public class CustomDataBus {
//    public static VehicleConfiData vehicleConfiData = new VehicleConfiData();
    public static HashMap<String, GsonFactoryConfig> gsonFactoryConfigMap = new HashMap<>();
    public static HashMap<String, List<DefaultComponentProvider>> gsonDefaultComponentProvidersMap = new HashMap<>();
    public static HashMap<ResourceLocation, DynamicResourcePack> dynamicResourcePackHashMap = new HashMap<>();
    public static List<GsonComponentFLRegistryC2SPacket> componentFLRegistryC2SPacketCacheList = new ArrayList<>();

    public static void load() {
        Config.makeSureExistsVPackFolder();
        for (Path path : Config.listDirectory(Config.VPackFolder)) {
//            System.out.println("Directory " + path);
            for (Path jsonPath : Config.listPath(path)) {
//                System.out.println("JSON " + jsonPath);
                String fileName = jsonPath.getFileName().toString();
                // 提取文件名（去掉扩展名）
                String name = fileName.contains(".")
                        ? fileName.substring(0, fileName.lastIndexOf('.'))
                        : fileName;
                String PACKNAME = jsonPath.getParent().getFileName().toString();
                System.out.println("PACK__NAME "+ PACKNAME);


                List<DefaultComponentProvider> componentProviderCacheList = new ArrayList<>();
                if (name.equals("components")) {
                    try (FileReader reader = new FileReader(jsonPath.toFile())) {
                        // 使用 JsonParser 解析文件内容
                        JsonElement jsonElement = JsonParser.parseReader(reader);

                        // 检查是否为 JsonObject 或 JsonArray
                        if (jsonElement.isJsonObject()) {
                            JsonObject jsonObject = jsonElement.getAsJsonObject();
                            ACHeli.GsonComponentFLRegisterMap.forEach((componentName, clazz) -> {
                                System.out.println("componentName " + componentName);
                                if (jsonObject.has(componentName)) {
                                    JsonArray array = jsonObject.getAsJsonArray(componentName);
                                    for (JsonElement element : array) {
                                        DefaultComponentProvider provider = DefaultComponentFactoryRegistry
                                                .registerForGsonDefaultComponentProvider(PACKNAME, componentName, element.toString());
                                        if (provider != null) {
                                            componentProviderCacheList.add(provider);
                                            componentFLRegistryC2SPacketCacheList.add(new GsonComponentFLRegistryC2SPacket
                                                    (PACKNAME, componentName, element.toString()));
                                            //发送网络包 让服务器也加载同样数据的provider

                                        } else {
                                            ACHeli.LOGGER.info("Provider == null");
                                        }

                                    }
                                    gsonDefaultComponentProvidersMap.put(PACKNAME, componentProviderCacheList);
                                }

                            });
                        }

                    } catch (Exception e) {
                        System.err.println("GsonComponent load error: " + e.getMessage());
                    }
                }

                if (name.equals("factory")) {
                    GsonFactoryConfig instance = new GsonFactoryConfig();
                    instance = (GsonFactoryConfig) Config.loadConfig(jsonPath, instance);
                    gsonFactoryConfigMap.put(PACKNAME, instance);
                    ACHFactories.initGsonEntities(PACKNAME, instance);

                    for (Path resPack : Config.listDirectory(path.resolve("resources"))) {
                        String resPackFileName = resPack.getFileName().toString();
                        for (Path resFile : Config.listPath(resPack)) {
//                            System.out.println("SCANTo "+ resFile);
                            String resFileName = resFile.getFileName().toString();
//                            String packId = PACKNAME+"_"+resFile;
                            ResourceLocation location = ResourceLocation.tryBuild(MODID, "%s/%s/%s".formatted(PACKNAME, resPackFileName, resFileName));
                            File file = resFile.toFile();
                            dynamicResourcePackHashMap.put(location,
                                    new DynamicResourcePack(
                                            location, resPackFileName, file,
                                            Config.fileToByteArrayStream(file)));
                        }

                    }

                }
            }
        }

    }
}
